package com.gl.framework.security.service;

import com.gl.common.enums.UserStatusEnum;
import com.gl.common.exception.BaseException;
import com.gl.common.util.StringUtils;
import com.gl.framework.security.LoginUser;
import com.gl.portal.system.service.SysRoleService;
import com.gl.portal.system.service.SysUserService;
import com.gl.portal.system.vo.SysUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 用户验证处理
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysRoleService roleService;

	@Autowired
	private SysPermissionService permissionService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		String loginName = username;
		SysUserVo user = userService.selectUserByLoginName(loginName);
		if (StringUtils.isNull(user)) {
			log.info("登录用户：{} 不存在.", loginName);
			throw new UsernameNotFoundException("登录用户：" + loginName + " 不存在");
		/*} else if (UserStatusEnum.DELETED.code().equals(user.getIsDeleted())) {
			log.info("登录用户：{} 已被删除.", loginName);
			throw new BaseException("对不起，您的账号：" + loginName + " 已被删除");*/
		} else if (UserStatusEnum.DISABLE.code().equals(user.getStatus())) {
			log.info("登录用户：{} 已被停用.", username);
			throw new BaseException("对不起，您的账号：" + loginName + " 已停用");
		}

		return createLoginUser(user);
	}

	/**
	 * 构建登录用户，存储更多用户信息
	 *
	 * @param user
	 * @return
	 */
	private UserDetails createLoginUser(SysUserVo user) {
		Long userId = user.getId();
		// 用户角色ID列表
		List<Long> roleIds = roleService.selectRoleListByUserId(userId);
		// 用户角色权限字符串组
		Set<String> roleKeys = roleService.selectRolePermissionByUserId(userId);
		// 部门数据权限列表
		List<Long> dataScopes = roleService.getUserDataScopes(userId);
		// 菜单权限标识列表
		Set<String> menuPermissionSet = permissionService.getMenuPermission(userId);

		return new LoginUser(user, roleIds, roleKeys, dataScopes, menuPermissionSet);
	}
}
